<template>
  <el-dialog :title="title" :visible.sync="visible" width="520px" append-to-body>
    <div class="qrcode-wrap">
      <div ref="qrcode" class="qrcode"></div>
    </div>
    <div class="link-line">
      <el-input v-model="link" readonly>
        <el-button slot="append" @click="copyLink" type="text">复制</el-button>
      </el-input>
    </div>
    <div style="text-align:center;margin-top:10px;">
      <el-button type="primary" @click="downloadQrcode">下载二维码</el-button>
    </div>
  </el-dialog>
</template>

<script>
import QRCode from 'qrcodejs2';
export default {
  name: 'LinkQrcodeDialog',
  data() {
    return { visible: false, link: '', qrcode: null ,title:''};
  },
  methods: {
    open(link,title) {
      this.title = title;
      this.visible = true;
      this.link = link;
      this.$nextTick(() => {
        if (this.$refs.qrcode) this.$refs.qrcode.innerHTML = '';
        this.qrcode = new QRCode(this.$refs.qrcode, { text: link, width: 200, height: 200 });
      });
    },
    copyLink() {
      this.$copyText(this.link).then(() => this.$message.success('已复制到剪贴板'));
    },
    downloadQrcode() {
      const img = this.$refs.qrcode.querySelector('img') || this.$refs.qrcode.querySelector('canvas');
      if (!img) return;
      let dataURL = '';
      if (img.tagName.toLowerCase() === 'img') {
        dataURL = img.src;
      } else {
        dataURL = img.toDataURL('image/png');
      }
      const a = document.createElement('a');
      a.href = dataURL;
      a.download = 'qrcode.png';
      a.click();
    }
  }
}
</script>

<style scoped>
.qrcode-wrap { display:flex; justify-content:center; }
.qrcode { width:200px; height:200px; }
.link-line { margin-top: 10px; }
</style>


